#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string>
using namespace std;

int main()
{
    int pipefd[2];
    if (pipe(pipefd) == -1) {
        perror("pipe");
        return 1;
    }
    pid_t pid = fork();//体现A进程创建B进程
    if (pid == -1) {
        perror("fork");
        return 1;
    }
    if (pid == 0) { //子进程
        close(pipefd[1]); //关闭写端
        while(true)
        {
            char buffer[100];
            int n = read(pipefd[0], buffer, sizeof(buffer));
            if (n > 0) {
                buffer[n] = '\0'; // Null-terminate the string
                cout << "Child received: " << buffer << endl;
            }
            else
                break; //管道读端关闭，退出循环
        }
        close(pipefd[0]);
        exit(0);
    }
    //父进程
    close (pipefd[0]); //关闭读端
    int cnt = 5;
    while(cnt--)
    {
        string msg = "Message " + to_string(5 - cnt);
        write(pipefd[1], msg.c_str(), msg.size());
        sleep(1);
    }
    close(pipefd[1]);
    int ret = waitpid(pid, nullptr, 0);
    if (ret == -1) {
        perror("waitpid");
        return 1;
    } 
    return 0;
}